package com.tqz.rc.spring.cloud.example.provider;

import com.tqz.rc.api.Instance;
import com.tqz.rc.client.naming.NamingService;
import com.tqz.rc.common.exception.RcException;
import com.tqz.rc.spring.cloud.TqzRcProperties;
import com.tqz.rc.spring.cloud.TqzRcServiceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2021/9/22 10:48
 */
@RestController
@RequestMapping("provider")
public class ProviderController implements EnvironmentAware {

    private Environment environment;

    @Autowired
    private TqzRcServiceManager serviceManager;

    @Autowired
    private TqzRcProperties properties;

    @Value("${spring.application.name}")
    private String serviceName;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @RequestMapping("test")
    public String test(String name) {
//        int i = 1 / 0;
        System.out.println("服务端口号为：" + environment.getProperty("server.port"));
        return "Hello " + name;
    }

    @RequestMapping("selectInstance")
    public List<Instance> selectInstance() throws RcException {
        NamingService namingService = serviceManager.getNamingService(properties.getTqzRcProperties());
        List<Instance> instances = namingService.selectInstances(serviceName);

        return instances;
    }
}
